import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import { logout } from '@/api/user'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API , // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (resp) =>{
    return resp
  },
  error => {
    const { status } = error.response
    if ( status === 401 ) {
      /**
       * token过期
       */
      // Message.error({ message: "登录状态已过期，请重新登录", duration: 5000})
      router.replace("/401")
      sessionStorage.removeItem('userInfo')
      sessionStorage.removeItem("token") // 删除token
    }
    return Promise.reject('登录状态已过期，请重新登录！')
  }
)

export default service
